<template>
    <view class="cleaning-order-container">
        <!-- 顶部信息栏 -->
        <z-nav-bar id="nav" bgColor="#ffffff" title="洗护下单"></z-nav-bar>
        <view class="top-info">
            <view class="title_info df justify-between mgb-20">
                <view class="flex1 df">
                    <text class="title_name">
                      {{shopInfo.storeShortName}}
                    </text>
                    <view class="shop_lable mgl-15">店铺</view>
                </view>
                <view class="more df flex-ac" @click="moreShop">
                    <text class="more_text">更多</text>
                    <up-icon name="arrow-right" color="#3c9cff" size="20"></up-icon>
                </view>
            </view>
            <view class="info-item df flex-col">
                <view class="info-left df flex-ac">
                    <up-icon name="clock" color="#b0b0b0" size="20"></up-icon>
                    <text class="mgl-20 info-item_time ">营业时间：{{shopInfo.onlineStartTime}}~{{shopInfo.onlineEndTime}}</text>
                </view>
<!--                <view class="width-120 mgt-24"> <up-button size="mini" type="primary" :plain="true"-->
<!--                        text="到店洗衣"></up-button></view>-->

            </view>
            <view class="shop_info mgt-30">
                <view class="df flex-jc-sb">
                    <view class="df shop_address flex-ac ">
                        <up-icon name="map-fill" color="#3c9cff" size="20"></up-icon>
                        <text class="mgl-15 es">{{shopInfo.storeLocation}}</text>
                    </view>
                    <view class="rund_km df mgr-15" @click="openMap">
                        <up-icon name="car-fill" color="#fff" size="20"></up-icon>
                        <text>{{km.toFixed(3)}}km</text>
                    </view>
                </view>
                <view class="df">
                    <view class="df ">
                        <up-icon name="phone-fill" color="#3c9cff" size="20"></up-icon>
                        <text class="mgl-15">{{shopInfo.customerServicePhone}}</text>
                    </view>
                </view>


            </view>
        </view>
        <view class="counp_num" @click="handleCounp()">
            <image class="cpunp_img"  mode="widthFix" src="@/static/img/shop_info.png"></image>

            <!-- <text>这里放店铺优惠卷</text> -->
        </view>
        <!-- 横向菜单 -->
        <view class="list_tab">
            <up-tabs :list="listTab" keyName="serviceName" @click="handleTab" :lineWidth="30" ></up-tabs>
        </view>
        <view class="height-20"></view>
        <!-- 主内容 -->
        <view class="content">
            <!-- 左侧一级分类 -->
            <scroll-view class="category-menu" scroll-y>
                <view v-for="(category, index) in categories" :key="index"
                    :class="['menu-item', { active: activeCategory === index }]" @click="selectCategory(index)">
                    <text>{{ category.name }}</text>
                    <view v-if="activeCategory === index" class="active_round"></view>
                </view>
            </scroll-view>
            <!-- 右侧商品列表 -->
        <scroll-view class="product-list" scroll-y @scroll="onScroll" :scroll-into-view="intoindex" id="right-list">
        <view v-for="(category, index) in categories" :key="index" :id="'category-' + index"
            :ref="'category-' + index" class="product-category">
            <view class="category-title">{{ category.name }}</view>
            <view class="product_list flex_">
                <view class="product-item " v-for="product in category.products" :key="product.id">
                    <image :src="product.clothingPicture" class="product-image" />
                    <view class="product-info">
                        <view class="product-name mgt-20">{{ product.clothingTypeName }}</view>
                        <view class="product-price mgt-20">¥{{ product.price }}</view>
                        <view class="product-actions df flex-jc-sb mgt-20">
                            <up-icon name="minus-circle" color="#3c9cff" size="20"
                                @click="decreaseQuantity(product)"></up-icon>
                            <text>{{ product.quantity? product.quantity : 0 }}</text>
                            <up-icon name="plus-circle-fill" color="#3c9cff" size="20"
                                @click="increaseQuantity(product)"></up-icon>
                        </view>
                    </view>
                </view>
            </view>
        </view>
                <!-- 添加占位高度 -->
                <view class="scroll-placeholder"></view>
            </scroll-view>
        </view>
        <!-- 底部结算栏 -->
        <view class="footer">
            <view class="cart">
<!--                <up-icon name="shopping-cart" color="#3c9cff" size="30"></up-icon>-->
<!--                <text class="cart-count">{{ cartCount }}</text>-->
            </view>
            <view class="df flex1 mgl-20 flex-jc-end flex-ac ">
                <view class="total flex1 mgr-20 ">洗护件数 ：<text class="red_a" >{{ cartCount }}</text> 件</view>
                <view class="width_150"> <up-button type="primary"  @click="submit" shape="circle" text="立即下单"></up-button></view>
            </view>


        </view>
         <ShopCoupon v-model="isCoupon" :couponList="couponList" @getCoupon="handleGetCoupon"></ShopCoupon>
    </view>
</template>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app';
import ShopCoupon from '@/components/shop-coupon/shop-coupon.vue'
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import {useCustomStores} from '@/utils/hook'
import { commonStore } from '@/stores/common'
const {ShopStore:{shopInfo},ShopStore} = useCustomStores()
const CommonStore =commonStore()
import {
  servicesGetAllWashingServices,
  allLargeListHema,
  typeQryByStoreld
} from '@/api/cleaningOrder'
import {
  couponListByStoreId,

} from '@/api/pagesShop'
const menus = reactive(['普洗', '精洗', '奢护洗', '空气洗']);
const isCoupon = ref(false);
const couponList = ref([])
const km = ref('0');
const activeMenu = ref(0);
const intoindex = ref(''); // 用于滚动到指定分类
const storeId = ref('')
const serviceNameType = ref('')
const deviceCode = ref('') //这里如果有这个值表示衣柜下单
let categories = ref([
    // {
    //     name: '上装',
    //     products: [
    //         { id: 1, name: '毛衫/绒衫', price: 60, image: 'https://img.alicdn.com/imgextra/i3/2000143913/O1CN017A4IgT1emCqMMFT1u_!!2000143913.jpg_.webp', quantity: 0 },
    //         { id: 2, name: '棉裤/羽绒裤', price: 98, image: 'https://img.alicdn.com/imgextra/i3/2000143913/O1CN017A4IgT1emCqMMFT1u_!!2000143913.jpg_.webp', quantity: 0 },
    //         { id: 3, name: '棉裤/羽绒裤', price: 98, image: 'https://img.alicdn.com/imgextra/i3/2000143913/O1CN017A4IgT1emCqMMFT1u_!!2000143913.jpg_.webp', quantity: 0 },
    //     ],
    // },
  // {
  //     name: '上装',
  //     products: [
  //         { id: 1, name: '毛衫/绒衫', price: 60, image: 'https://img.alicdn.com/imgextra/i3/2000143913/O1CN017A4IgT1emCqMMFT1u_!!2000143913.jpg_.webp', quantity: 0 },
  //         { id: 2, name: '棉裤/羽绒裤', price: 98, image: 'https://img.alicdn.com/imgextra/i3/2000143913/O1CN017A4IgT1emCqMMFT1u_!!2000143913.jpg_.webp', quantity: 0 },
  //         { id: 3, name: '棉裤/羽绒裤', price: 98, image: 'https://img.alicdn.com/imgextra/i3/2000143913/O1CN017A4IgT1emCqMMFT1u_!!2000143913.jpg_.webp', quantity: 0 },
  //     ],
  // },
]);
let categoriesSection = ref(new Map()); // 用Map存储所有tab下选中的商品
let listTab = ref([]);
const activeCategory = ref(0);
const totalPrice = ref(0);
const cartCount = ref(0);
let categoryHeights = ref<number[]>([]);
let isClickingMenu = ref(false); // 标记是否是点击左侧菜单触发的滚动

const selectMenu = (index: number) => {
    activeMenu.value = index;
};

const selectCategory = (index: number) => {
    isClickingMenu.value = true; // 标记为点击菜单触发
    activeCategory.value = index;
    intoindex.value = `category-${index}`; // 设置滚动到的目标元素ID
    setTimeout(() => {
        isClickingMenu.value = false; // 延迟重置标记，确保滚动完成后再允许同步
    }, 300);
};

const onScroll = (event: any) => {
    if (isClickingMenu.value) return;

    const scrollTop = event.detail.scrollTop;
    const containerHeight = event.detail.scrollHeight;
    const threshold = 50;

    // Find visible categories
    for (let i = 0; i < categoryHeights.value.length; i++) {
        const currentTop = categoryHeights.value[i];
        const nextTop = categoryHeights.value[i + 1] || containerHeight;

        if (scrollTop >= currentTop - threshold && scrollTop < nextTop - threshold) {
            if (i !== activeCategory.value) {
                activeCategory.value = i;
            }
            break;
        }
    }
};
//店铺优惠卷
const loadCouponList = (res)=>{
  couponListByStoreId({
    storeId:shopInfo.value.storeId,
    pageNum:1,
    pageSize:30
  }).then(res=>{
    couponList.value = res
    console.log(res,'res')
  })
}
function getDistance(lat1, lng1, lat2, lng2) {
  const R = 6371000; // 地球平均半径，单位：米
  const φ1 = lat1 * Math.PI / 180;
  const φ2 = lat2 * Math.PI / 180;
  const Δφ = (lat2 - lat1) * Math.PI / 180;
  const Δλ = (lng2 - lng1) * Math.PI / 180;

  const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
    Math.cos(φ1) * Math.cos(φ2) *
    Math.sin(Δλ/2) * Math.sin(Δλ/2);

  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

  return R * c/1000; // 返回两点间的距离，单位：米
}
const calculateCategoryHeights = () => {
    nextTick(() => {
        const query = uni.createSelectorQuery();
        query.selectAll('.product-category').boundingClientRect((rects: any[]) => {
            if (rects) {
                let offset = 0;
                categoryHeights.value = rects.map(rect => {
                    const result = offset;
                    offset += rect.height;
                    return result;
                });
            }
        }).exec();
    });
};

const increaseQuantity = (product: any) => {
    product.quantity = (product.quantity || 0) + 1;

    // 更新或添加到 categoriesSection
    let selectedProducts = categoriesSection.value.get(serviceNameType.value) || [];
    let existingProduct = selectedProducts.find(p => p.id === product.id);

    if (existingProduct) {
        existingProduct.quantity = product.quantity;
    } else {
        selectedProducts.push({...product});
    }
    categoriesSection.value.set(serviceNameType.value, selectedProducts);

    calculateTotal();
};

const decreaseQuantity = (product: any) => {
    if (product.quantity > 0) {
        product.quantity -= 1;

        // 更新 categoriesSection
        let selectedProducts = categoriesSection.value.get(serviceNameType.value) || [];
        let existingProduct = selectedProducts.find(p => p.id === product.id);

        if (existingProduct) {
            if (product.quantity === 0) {
                // 如果数量为0，从数组中移除
                selectedProducts = selectedProducts.filter(p => p.id !== product.id);
            } else {
                existingProduct.quantity = product.quantity;
            }
            categoriesSection.value.set(serviceNameType.value, selectedProducts);
        }

        calculateTotal();
    }
};

const calculateTotal = () => {
    let total = 0;
    let count = 0;

    // 只遍历categoriesSection中的商品来计算总价和数量
    categoriesSection.value.forEach((products) => {
        products.forEach(product => {
            if (product.quantity > 0) {
                total += product.price * product.quantity;
                count += product.quantity;
            }
        });
    });

    totalPrice.value = total;
    cartCount.value = count;
};

const checkout = () => {
    console.log('下单成功，总金额：', totalPrice.value);
};
const loadServicesGetAllWashingServices =()=>{
  servicesGetAllWashingServices(storeId.value).then(res=>{
     listTab.value=res
    if(res.length>0){
      let type = res[0].serviceName
      let id = res[0].id
      serviceNameType.value = type
      loadTypeQryByStoreId(type,id).then(() => {
        // 恢复保存的商品状态
        const savedProducts = categoriesSection.value.get(type) || [];
        categories.value.forEach(category => {
          category.products.forEach(product => {
            const savedProduct = savedProducts.find(p => p.id === product.id);
            if(savedProduct) {
              product.quantity = savedProduct.quantity || 0;
            }
          });
        });
        calculateTotal();
      })
    }

  })
}
/**加载分类函数***/
const loadTypeQryByStoreId =(type,id)=>{
  return typeQryByStoreld({
    storeId:storeId.value,
    washingMethod:type,
    id
  }).then(res=>{
    categories.value = res;
    return res;
  })
}
/****处理tab*****/
const handleTab =(e)=>{
  let {serviceName,id} = e;

  // 1. 保存当前tab的选中状态到Map中
  const currentProducts = [];
  categories.value.forEach(category => {
    category.products.forEach(product => {
      if(product.quantity > 0) {
        currentProducts.push({...product});
      }
    });
  });
  if(currentProducts.length > 0) {
    categoriesSection.value.set(serviceNameType.value, currentProducts);
  }

  const oldType = serviceNameType.value;
  serviceNameType.value = serviceName;

  // 2. 加载新分类数据
  loadTypeQryByStoreId(serviceName, id).then(() => {
    // 3. 从缓存中恢复之前的选择状态
    const savedProducts = categoriesSection.value.get(serviceName) || [];
    categories.value.forEach(category => {
      category.products.forEach(product => {
        const savedProduct = savedProducts.find(p => p.id === product.id);
        if(savedProduct && savedProduct.quantity > 0) {
          product.quantity = savedProduct.quantity;
        } else {
          product.quantity = 0;
        }
      });
    });

    calculateTotal();
  });
}
const loadAllLargeListHema =()=>{
  allLargeListHema(storeId.value)

}

const submit =()=>{
  if(cartCount.value<= 0){
    return
  }

  // 收集所有已选商品
  let allSelectedProducts = [];
  categoriesSection.value.forEach((products) => {
    allSelectedProducts = allSelectedProducts.concat(products.filter(p => p.quantity > 0));
  });

  ShopStore.setPlaceOrderInfo({
    storeId:storeId.value,
    categories:allSelectedProducts,
    cartCount:cartCount.value,
    totalPrice:totalPrice.value,
    washingMethod:serviceNameType.value,
  })
  console.log('submit',serviceNameType.value,)
  let url = '/pages/cleaningOrder/orderConfirmation'
  if(deviceCode.value){
    url = '/pages/cleaningOrder/orderConfirmation?deviceCode='+deviceCode.value
  }
  uni.navigateTo({
    url
  })
}
function moreShop(){
  uni.navigateTo({
    url:'/pages/cleaningOrder/moreShop'
  })
}
const handleCounp = ()=>{
      
      if(!shopInfo.idCouponEnabled){
        uni.showToast({
          title: '该店铺暂无优惠卷',
          icon: 'none'
        })
        return
      }
   isCoupon.value = true

}
//领取优惠卷
const handleGetCoupon = ({item, callback})=>{
  if(!item.available) {
    uni.showToast({
      title: '该券已领取或不可领取',
      icon: 'none'
    });
    return;
  }

  couponAdd({
    couponId: item.couponId,
    userId: userInfo.userId,
    status: 0
  }).then(res => {
    uni.showToast({
      title: '领取成功',
      icon: 'none',
      duration: 2000
    });

    // 执行回调更新子组件状态
    if(callback) callback();
  })
}
/****取选中的数据商品*******/
function filterProductsWithQuantity(categories) {
  return categories.flatMap(category =>
    category.products.filter(product => product.quantity > 0)
  );
}
onLoad((options)=>{
  storeId.value = options.storeId
  if(options.device_code){
    deviceCode.value = options.device_code
  }
  loadServicesGetAllWashingServices()
  loadAllLargeListHema()
  loadCouponList()
})
onMounted(() => {
    calculateCategoryHeights();
});
//计算距离
console.log('CommonStore.cityInfo',shopInfo)
let location = shopInfo.location.split(',')
//
 km.value = getDistance(location[0],location[1],CommonStore.cityInfo.latitude,CommonStore.cityInfo.longitude)
const openMap = () => {
    uni.openLocation({
        latitude: Number(location[0]),
        longitude: Number(location[1]),
        name: shopInfo.storeShortName,
        address: shopInfo.storeLocation,
        scale: 18
    });
}
// 监听分类数据变化重新计算高度
watch(() => categories.value, () => {
    nextTick(() => {
        calculateCategoryHeights();
    });
}, { deep: true });
</script>

<style lang="scss" scoped>
.cleaning-order-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.top-info {
    box-sizing: border-box;
    width: 100%;
    padding: 32rpx;
    background-color: #ffffff;

    .shop_info {
        width: 100%;

        .shop_address {
            font-size: 28rpx;
            color: 32rpx;
            flex: 1;

            .es {
                width: 440rpx;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
            }
        }

        .rund_km {

            padding: 10rpx 15rpx;
            border-radius: 20rpx;
            background-color: #3c9cff;
            font-size: 28rpx;
            color: #ffffff
        }

    }
}
.more_text{
    font-size: 28rpx;
}
.title_info{
    .title_name{
        font-size: 32rpx;
        font-weight: bold;
    }
    .shop_lable{
        padding: 5rpx 10rpx;
        background-color: #3c9cff;
        font-size: 24rpx;
        color: #ffffff;
        height: 40rpx;
        border-radius: 5rpx;
    }

}
.counp_num {
    width: 100%;
    // height: 200rpx;
    .cpunp_img{
        width: 100%;
        display: block;
        // height: ;
        // height: auto;
        // margin-bottom: 10rpx;
    }
}

.list_tab {
    box-sizing: border-box;
    width: 100%;
    padding: 32rpx 0;
    background-color: #ffffff;
}

.info-item {
    .info-item_time {
        font-size: 28rpx;
        color: #b0b0b0;
    }
}

.info-button {
    background-color: #007aff;
    color: #ffffff;
    padding: 10rpx 20rpx;
    border-radius: 10rpx;
}

.distance {
    color: #999999;
}

.horizontal-menu {
    display: flex;
    background-color: #ffffff;
    padding: 20rpx 0;
}

.menu-tab {
    padding: 20rpx 40rpx;
    cursor: pointer;
}

.menu-tab.active {
    color: #007aff;
    font-weight: bold;
}

.banner {
    margin: 20rpx 0;
}

.banner-image {
    width: 100%;
    height: auto;
}

.content {
    display: flex;
    flex: 1;
    overflow: hidden;
}

.category-menu {
    width: 200rpx;
    background-color: #f5f5f5;
    overflow-y: auto;
}

.menu-item {
    position: relative;
    width: 180rpx;
    text-align: center;
    height: 100rpx;
    border-radius: 0 20rpx 20rpx 0;
    line-height: 100rpx;

    .active_round {
        width: 50rpx;
        /* 半圆的直径 */
        height: 25rpx;
        /* 半圆的半径 */
        background-color: #3c9cff;
        /* 半圆的颜色 */
        border-top-left-radius: 25rpx;
        /* 左上角圆角 */
        border-top-right-radius: 25rpx;
        /* 右上角圆角 */
        position: absolute;
        left: -25rpx;
        /* 贴着左边 */
        top: 50%;
        /* 垂直居中 */
        transform: translateY(-50%) rotate(90deg);
        /* 垂直居中并旋转 90 度 */
        transform-origin: center;
        /* 旋转中心 */
    }
}

.menu-item.active {
    background-color: #ffffff;
    font-weight: bold;
}

.product-list {
    box-sizing: border-box;
    flex: 1;
    overflow-y: auto;
    padding: 20rpx;
    background-color: #ffffff;
    border-radius: 20rpx;
}

.product-category {
    margin-bottom: 40rpx;
}

.category-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
}

.product_list {
    display: flex;
    flex-wrap: wrap;

    justify-content: space-between;
    &.product_list:after {
        // 使用伪类元素占据单位，不影响页面
        content: "";
        height: 0;
        width: 150rpx;
    }
}

.product-item {
    display: flex;
    flex-direction: column;
    //   justify-content: space-between;
    width: 150rpx;

    //   height: 150rpx;
    //   margin-bottom: 20rpx;

}

.product-image {
    width: 150rpx;
    height: 150rpx;
    margin-right: 20rpx;
    border-radius: 20rpx;
}

.product-info {
    flex: 1;
}

.product-name {
    font-size: 28rpx;
    margin-bottom: 10rpx;
}

.product-price {
    color: #ff4d4f;
    margin-bottom: 10rpx;
}

.product-actions {
    display: flex;
    align-items: center;
}

.product-actions button {
    width: 60rpx;
    height: 60rpx;
    text-align: center;
    line-height: 60rpx;
    background-color: #f5f5f5;
    border: none;
    cursor: pointer;
}

.footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    background-color: #ffffff;
    border-top: 2rpx solid #f0f0f0;
}

.cart {
    display: flex;
    align-items: center;
    position: relative;
}

.cart-icon {
    width: 60rpx;
    height: 60rpx;
}

.cart-count {
    position: absolute;
    right: -10rpx;
    top:-10rpx;
    margin-left: 10rpx;
    color: #ffffff;
    width: 35rpx;
    height: 35rpx;
    border-radius: 50%;
    background-color:#ff4d4f ;
    font-size: 24rpx;
    text-align: center;
}

.total {
    font-size: 32rpx;
    font-weight: bold;
    text-align: right;
}

.checkout-button {
    background-color: #ff4d4f;
    color: #ffffff;
    padding: 20rpx 40rpx;
    border: none;
    border-radius: 10rpx;
    cursor: pointer;
}

.scroll-placeholder {
    height: 90rpx; /* 占位高度，确保滚动到最后一个分类时菜单高亮 */
}
.red_a{
    color: #ff4d4f;
}
</style>
